#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "bsp_headers.h"
#include "init.h"

uint8_t             programState_ADC_Initialized = 0x00;
volatile uint64_t   programState_restTicks = 0x0;
volatile uint64_t   programState_globalTicks = 0x0;
volatile double     programState_ticksPerCnt = -1.0;

Device_TTP223           *gdv_TTP223_1;
volatile Device_LED     *gdv_LED_B2;

void User_SyncTicksPerCnt(void);

int main(void){
    SysTick_Config(SystemCoreClock/1000000);
    BSP_DelayMs(10);
    
    User_SyncTicksPerCnt();
    User_InitUsart1(USART1_BAUDRATE);

    Device_TTP223 dv_TTP223_1 = User_InitTTP223_1();
    gdv_TTP223_1 = &dv_TTP223_1;
    
    Device_LED dv_LED_B2 = User_InitLED_B2();
    gdv_LED_B2 = &dv_LED_B2;
    
    Device_PressureSensor dv_PS_PA5_ADC1 =  User_InitPressureSensor_PA5_ADC1();

    printf("Test USART 1, using Baud rate: %d\r\n", USART1_BAUDRATE);
    
    printf("Test LED, LED B2 is flashing...\r\n");
    
    BSP_LED_Flash(&dv_LED_B2, 100000, 10, 0U);

    uint8_t stateOf_dv_TTP223_1 = 0x00;
    uint16_t dataOf_dv_PS_PA5_ADC1 = 0x0000;
    double voltage = -1.0;
    

    while(1){
        stateOf_dv_TTP223_1 = BSP_TTP223_ReadAndUpdate(&dv_TTP223_1);
        dataOf_dv_PS_PA5_ADC1 = BSP_PressureSensor_SampleAndReadData(&dv_PS_PA5_ADC1, 5);
        voltage = ((double)dataOf_dv_PS_PA5_ADC1)/(4095.0)*3.3;
        printf("TTP223 state: ");
        if(stateOf_dv_TTP223_1 == 0x00){
            printf("OFF\r\n");
        }else{
            printf("ON\r\n");
        }
        printf("Pressure sensor data: 0x%04x; Voltage: %.4f\r\n", dataOf_dv_PS_PA5_ADC1, voltage);
        
        BSP_DelayMs(500);
        BSP_LED_Flash(&dv_LED_B2, 10000, 1, 0U);
    }
}

void User_TimingDelayDecrement(void){
    if(programState_restTicks != 0){
        programState_restTicks--;
    }
    programState_globalTicks ++;
}

int fputc(int ch, FILE *f){
    BSP_UsartSendByte(USART1, ch);
    return ch;
}

void User_EXTI0_IRQHandler(void){
    if(EXTI_GetITStatus(EXTI_Line0) != RESET){
        uint8_t state = BSP_TTP223_ReadAndUpdateIrq(gdv_TTP223_1, 1);
        printf(">>> TTP223: State changed! Current state: ");
        if(state!=0x00){
            printf("ON <<<\r\n");
        }else{
            printf("OFF <<<\r\n");
        }
        EXTI_ClearITPendingBit(EXTI_Line0);
    }
}

void User_SyncTicksPerCnt(void){
    uint64_t t1 = programState_globalTicks;
    int t2 = 100000;
    while(t2!=0){
        t2--;
    }
    uint64_t t3 = programState_globalTicks;
    programState_ticksPerCnt = (t3-t1) / 100000.0;

}
